<template>
  <div class="form-rules-container layout-pd" style="text-align: left">
    <el-form :model="queryParams" size="default" inline label-width="100px" class="mt35 mb35">
      <el-form-item label="角色名称" style="text-align: left">
        <el-input v-model="queryParams.name" placeholder="请输入角色名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="roleSearch">搜索</el-button>
        <el-button>重置</el-button>
      </el-form-item>
      <el-row>
        <el-col :span="24">
          <el-button type="primary" @click="handleOpen">新增</el-button>
        </el-col>
      </el-row>
    </el-form>
    <div>
      <el-table :data="roleData">
        <el-table-column label="ID" prop="id"></el-table-column>
        <el-table-column label="角色名称" prop="name"></el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleOpen(scope.row)">修改</el-button>
            <el-button link type="primary" size="small" @click="delRole(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog
        v-model="dialogVisible"
        title="编辑角色"
        width="30%"
        :before-close="handleClose"
    >
      <el-form :model="roleForm">
        <el-form-item label="角色名称">
          <el-input v-model="roleForm.name" placeholder="填写角色名称"></el-input>
        </el-form-item>
        <el-form-item label="功能菜单">
          <el-tree
              ref="checkMenu"
              show-checkbox
              node-key="id"
              style="max-width: 600px"
              :data="menuData"
              :default-expand-all="true"
              :default-checked-keys="roleMenus.menuIds"
              :props="defaultProps"
          />
        </el-form-item>
      </el-form>
      <template #footer>
			<span class="dialog-footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitForm">提交</el-button>
			</span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {getCurrentInstance, onMounted, reactive, ref, toRefs} from "vue";
import {ElMessage} from "element-plus";

export default {
  setup() {
    // 引用全局axios
    const axios = getCurrentInstance().appContext.config.globalProperties.$axios;
    // 设置下拉菜单节点
    const defaultProps = ref({
      label: 'name',
      children: 'children'
    })
    // 获取后台菜单数据，修改使用
    const roleMenus = ref({
      menuIds: [],
      rid: '',
    })
    // 获取菜单树形数据
    const checkMenu = ref([])
    // 数据对象集合
    const state = reactive({
      queryParams: {},
      roleForm: {},
      roleData: [],
      menuData: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      dialogVisible: false
    })
    // 弹出框打开
    const handleOpen = (row) => {
      state.dialogVisible = true
      if (row.id) {
        state.roleForm = row
        // 根据角色ID获取菜单数据
        axios.get(`/role/getRoleMenus/${row.id}`).then(res => {
          roleMenus.value.rid = row.id
          roleMenus.value.menuIds = res.data.data
        })
      } else {
        state.roleForm = {}
      }
    }
    // 弹出框关闭
    const handleClose = () => {
      state.dialogVisible = false
      state.roleForm = {}
    }
    // 删除角色
    const delRole = async (id) => {
      await axios.delete(`/role/${id}`)
      ElMessage.success('删除成功')
      await roleSearch()
    }
    // 角色搜索
    const roleSearch = async () => {
      let res = await axios.post('/role/5/1', state.queryParams);
      state.roleData = res.data.data;
    }
    // 获取菜单树形数据
    const getMenus = async () => {
      let res = await axios.get('/menu/getAllMenus');
      state.menuData = res.data.data;
    }
    // 提交表单
    const submitForm = async () => {
      // 获取选中的数据
      const checkedKeys = checkMenu.value.getCheckedKeys();
      // 判断是否是修改
      if (roleMenus.value.rid === '') {
        axios.post("/role/add", {
          name: state.roleForm.name,
          menus: checkedKeys
        }).then(res => {
          console.log(res)
          if (res.data.code === "1") {
            ElMessage.success("新增成功")
            state.dialogVisible = false
          } else {
            ElMessage.error(res.msg);
          }
        })
      } else {
        axios.put(`/role/${roleMenus.value.rid}`, {
          name: state.roleForm.name,
          menus: checkedKeys
        }).then(res => {
          if (res.data.code === "1") {
            ElMessage.success("修改成功")
            state.dialogVisible = false
          } else {
            ElMessage.error(res.msg);
          }
        })
      }
    }
    // 页面加载时初始化数据
    onMounted(() => {
      roleSearch()
      getMenus()
    })
    // 返回数据
    return {
      ...toRefs(state),
      roleSearch,
      handleOpen,
      handleClose,
      delRole,
      submitForm,
      getMenus,
      defaultProps,
      roleMenus,
      checkMenu
    }
  }
}
</script>
